const merge = require('webpack-merge');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const cssnano = require('cssnano');
const baseConfig = require('./webpack.base');


const prodConfig = {
  mode: 'production',
  plugins: [
    new OptimizeCssAssetsWebpackPlugin({
      assetNameRegExp: /\.css$/g,
      cssProcessor: cssnano,
    }),

    new MiniCssExtractPlugin({
      filename: '[name]_[contenthash:8].css',
    }),
    function ErrorPlugin() {
      // webpack3
      // this.plugin('done', () => {})
      this.hooks.done.tap('done', (stats) => {
        if (stats.compilation.errors
                    && stats.compilation.errors.length
                    && process.argv.indexOf('--watch') === -1) {
          console.log('build error'); // eslint-disable-line
          process.exit(1);
        }
      });
    },
  ],
  optimization: {
    splitChunks: {
      minSize: 0, // 0, 1000
      cacheGroups: {
        commons: {
          // test: /(react|react-dom)/,
          name: 'vendors', // vendors, commons
          chunks: 'all',
          minChunks: 2, // 2, 3
        },
      },
    },
  },
};

module.exports = merge(baseConfig, prodConfig);
